import { useLayoutEffect, useMemo, useRef, useState } from 'react';
import ReactDOM from 'react-dom';

const usePortal = function (Comp: React.ReactNode, refreshDeps: any[]) {
  const ref = useRef<HTMLElement>();
  const [frame, setFrame] = useState({});

  const keepAliveEl = useMemo(() => {
    const el = document.createElement('div');
    el.style.height = '100%';
    return el;
  }, []);

  useLayoutEffect(() => {
    if (!ref.current) {
      const animate = requestAnimationFrame(() => setFrame({}));
      return () => cancelAnimationFrame(animate);
    }

    const dom = ref.current;
    dom.append(keepAliveEl);

    return () => {
      dom.removeChild(keepAliveEl);
    };
  }, [keepAliveEl, frame, ...refreshDeps]);

  return {
    ref,
    Content: ReactDOM.createPortal(Comp, keepAliveEl),
  };
};

export default usePortal;
